<?php
if(isset($__ts)) unset($__ts);
$__ts = array();

global $blog, $service, $__ts;
# Locale language file support, defualt is en-us.php
if (!isset($blog['blogLanguage'])) {
	$blog['blogLanguage'] = $service['language'];
}
// Locale language file support.
switch($blog['blogLanguage']) {
	case "zh-TW":
	case "zh-CN":
		$languageFile ='lang/'.$blog['blogLanguage'].'.php';
	break;
	default:
		$languageFile = "";
}
if(!empty($languageFile)) { include ($languageFile); }

function CT_textcube_Plugin_N_Skin($target) {
	global $service, $pluginURL, $blog;
	requireComponent("Eolin.PHP.Core");
	require_once ('lang/pluginLocal.php');
	
	ob_start();
	?>
	<script type="text/javascript">
		function selectAddonTab(obj1, obj2, obj3, obj4){
			document.getElementById(obj1).className = "selected-tab";
			document.getElementById(obj2).className = "no-selected-tab";
			document.getElementById(obj3).className = "no-selected-tab";
			document.getElementById(obj4).className = "no-selected-tab";
		}

		function searchAddon() {
			var keyword = document.getElementById("searchAddonkey");
			var searchItem = document.getElementById("searchItem");
			if(keyword.value.trim() != "")
				window.open("http://textcube.org/" + searchItem.value  + "/search/" + looseURIEncode(keyword.value));
			return false;
		}
	</script>
	<div class="Addon_center">
		<div class="Addon_layout_menu_tab">
			<ul class="Addon-tabs-box">
				<li id="Addon-tab-1" class="selected-tab" onclick="selectAddonTab('Addon-tab-1', 'Addon-tab-2', 'Addon-tab-3', 'Addon-tab-4');hideLayer('CT_Addon4');hideLayer('CT_Addon3');hideLayer('CT_Addon2');showLayer('CT_Addon1');"><?php echo pluginLang::plts('함께보기');?></li>
				<li id="Addon-tab-2" class="no-selected-tab" onclick="selectAddonTab('Addon-tab-2', 'Addon-tab-1', 'Addon-tab-3', 'Addon-tab-4');hideLayer('CT_Addon4');hideLayer('CT_Addon3');hideLayer('CT_Addon1');showLayer('CT_Addon2');"><?php echo pluginLang::plts('플러그인');?></li>
				<li id="Addon-tab-3" class="no-selected-tab" onclick="selectAddonTab('Addon-tab-3', 'Addon-tab-1', 'Addon-tab-2', 'Addon-tab-4');hideLayer('CT_Addon4');hideLayer('CT_Addon2');hideLayer('CT_Addon1');showLayer('CT_Addon3');"><?php echo pluginLang::plts('스킨');?></li>
				<li id="Addon-tab-4" class="no-selected-tab" onclick="selectAddonTab('Addon-tab-4', 'Addon-tab-1', 'Addon-tab-2', 'Addon-tab-3');hideLayer('CT_Addon3');hideLayer('CT_Addon2');hideLayer('CT_Addon1');showLayer('CT_Addon4');"><?php echo pluginLang::plts('검색');?></li>
			</ul>
		</div>	
	<?
	$target .= ob_get_contents();
	ob_end_clean();

	$recentRssURLS = array('http://textcube.org/plugin/plugin/newRecentRSS?blogname=all', 'http://textcube.org/plugin/plugin/newRecentRSS?blogname=plugin', 'http://textcube.org/plugin/plugin/newRecentRSS?blogname=theme');
	$OL_CNT = 0;
	foreach ($recentRssURLS as $recentRssURL){
		$OL_CNT++;
		if(!is_null(getServiceSetting('TextcubePSAddon'.$OL_CNT))) {
			$AddonEntries = unserialize(getServiceSetting('TextcubePSAddon'.$OL_CNT));
			$result = 0;
		} else {
			list($result, $feed, $xml, $AddonEntries) = CT_textcube_Plugin_N_Skin_getRemoteFeed($recentRssURL);
			setServiceSetting('TextcubePSAddon'.$OL_CNT,serialize($AddonEntries));
		}
		if ($result == 0) {
			if (count($AddonEntries) > 0) {
				$target .= '<ol id="CT_Addon' . $OL_CNT . '" style="display:' . ($OL_CNT == 1 ? 'block' : 'none') . ';" class="Addon_list">'.CRLF;
				$i = 0;
				foreach($AddonEntries as $item) {
					$target .= '<li>'.CRLF;
					$target .= '	<div class="previewBox" style="background: url('.$pluginURL.'/images/thumbBacground.png) center center no-repeat;">'.CRLF;
					$target .= '		<img src="' . $item['image'] . '" onclick="window.open(\''. $item['permalink'] . '\');" border="0" width="32" height="32" />'.CRLF;
					$target .= '	</div>'.CRLF;
					$target .= '	<div class="entryInfo">'.CRLF;
					$target .= '		<a href="'. $item['permalink'] . '" onclick="return openLinkInNewWindow(this);" >'.CRLF;
					$blogName = strpos($item['permalink'], 'plugin')!== false ? 'plugin' : 'theme';
					$target .= '			<span class="date">' . Timestamp::formatDate($item['written']) . '</span> ' . ($OL_CNT == 1 ? '<span class="blogName">[' . ucwords($blogName) . ']</span>' : '') . '<br/>'.CRLF;
					$target .= '			<span class="title">' . UTF8::lessenAsEm(htmlspecialchars($item['title']),33) . '</span>'.CRLF;
					$target .= '		</a>'.CRLF;
					$target .= '	</div>'.CRLF;
					$target .= '</li>'.CRLF;
					if($i>3) break;
					else $i++;
				}
				$target .= '</ol>'.CRLF;
			} else {
				$target .= '<ol id="CT_Addon' . $OL_CNT . '" style="display:' . ($OL_CNT == 1 ? 'block' : 'none') . ';" class="Addon_list">'.CRLF;
				$target .= '	<p style="height: 90px; padding-top: 65px; text-align: center;">'._t('데이터가 없습니다.').'</p>';
				$target .= '</ol>'.CRLF;
			}
		} else {
			$target .= '<ol id="CT_Addon' . $OL_CNT . '" style="display:' . ($OL_CNT == 1 ? 'block' : 'none') . ';" class="Addon_list">'.CRLF;
			$target .= '	<p style="height: 90px; padding-top: 65px; text-align: center;">'._t('데이터를 가져올 수 없습니다.').'<br />'._t('잠시 후 다시 시도해 주십시오.').'</p>'.CRLF;
			$target .= '</ol>'.CRLF;
		}
	}
	$target .= '<ol id="CT_Addon4" style="display:none;" class="Addon_list">'.CRLF;
	$target .= '	<div class="searchBox">'.CRLF;
	$target .= '		<select id="searchItem"><option value="plugin">'.pluginLang::plts('플러그인').'</option><option value="theme">'.pluginLang::plts('스킨').'</option></select>'.CRLF;
	$target .= '		<input type="text" size="12" id="searchAddonkey" name="searchAddonkey" value="" onkeypress="if (event.keyCode == 13) { searchAddon(); return false; }" class="searchfield" />'.CRLF;
	$target .= '		<input type="button" size="8" value="'.pluginLang::plts('검 색').'" onclick="searchAddon();" class="searchbutton" />'.CRLF;
	$target .= '	</div>'.CRLF;
	$target .= '</ol>'.CRLF;
	$target .= "</div>";
	unset($feed);
	unset($xmls);
	unset($AddonEntries);
	return $target;
}

function CT_textcube_Plugin_N_Skin_getRemoteFeed($url) {
	global $service;
	$xml = fireEvent('GetRemoteFeed', null, $url);
	if (empty($xml)) {
		requireComponent('Eolin.PHP.HTTPRequest');
		$request = new HTTPRequest($url);
		$request->timeout = 3;
		if (!$request->send())
			return array(2, null, null, null);
		$xml = $request->responseText;
	}
	$feed = array('xmlURL' => $url);
	$xmls = new XMLStruct();
	if (!$xmls->open($xml, $service['encoding'])) {
		if(preg_match_all('/<link .*?rel\s*=\s*[\'"]?alternate.*?>/i', $xml, $matches)) {
			foreach($matches[0] as $link) {
				$attributes = getAttributesFromString($link);
				if(isset($attributes['href'])) {
					$urlInfo = parse_url($url);
					$rssInfo = parse_url($attributes['href']);
					$rssURL = false;
					if(isset($rssInfo['scheme']) && $rssInfo['scheme'] == 'http')
						$rssURL = $attributes['href'];
					else if(isset($rssInfo['path'])) {
						if($rssInfo['path']{0} == '/')
							$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}{$rssInfo['path']}";							
						else
							$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}".(isset($urlInfo['path']) ? rtrim($urlInfo['path'], '/') : '').'/'.$rssInfo['path'];
					}
					if($rssURL && $url != $rssURL)
						return CT_textcube_Plugin_N_Skin_getRemoteFeed($rssURL);
				}
			}
		}
		return array(3, null, null, null);
	}
	if ($xmls->getAttribute('/rss', 'version')) {
		$feed['blogURL'] = $xmls->getValue('/rss/channel/link');
		$feed['title'] = $xmls->getValue('/rss/channel/title');
		$feed['description'] = $xmls->getValue('/rss/channel/description');
		if (Validator::language($xmls->getValue('/rss/channel/language')))
			$feed['language'] = $xmls->getValue('/rss/channel/language');
		else if (Validator::language($xmls->getValue('/rss/channel/dc:language')))
			$feed['language'] = $xmls->getValue('/rss/channel/dc:language');
		else
			$feed['language'] = 'en-US';
		$feed['modified'] = gmmktime();
		$items = array();
		for ($i = 0; $link = $xmls->getValue("/rss/channel/item[$i]/link"); $i++) {
			$item = array('permalink' => rawurldecode($link));
			$item['title'] = $xmls->getValue("/rss/channel/item[$i]/title");
			$item['image'] = $xmls->getValue("/rss/channel/item[$i]/image");
			$item['author'] = $xmls->getValue("/rss/channel/item[$i]/author");
			$item['author'] = str_replace(array('(',')'), array('',''), $item['author']);
			if ($xmls->getValue("/rss/channel/item[$i]/pubDate"))
				$item['written'] = parseDate($xmls->getValue("/rss/channel/item[$i]/pubDate"));
			else if ($xmls->getValue("/rss/channel/item[$i]/dc:date"))
				$item['written'] = parseDate($xmls->getValue("/rss/channel/item[$i]/dc:date"));
			else
				$item['written'] = 0;
			array_push($items, $item);
		}
	} else
		return array(3, null, null, null);

	$feed['blogURL'] = POD::escapeString(UTF8::lessenAsEncoding(UTF8::correct($feed['blogURL'])));
	$feed['title'] = POD::escapeString(UTF8::lessenAsEncoding(UTF8::correct($feed['title'])));
	$feed['description'] = POD::escapeString(UTF8::lessenAsEncoding(UTF8::correct(stripHTML($feed['description']))));

	return array(0, $feed, $xml, $items);
}

function CT_textcube_Plugin_N_Skin_sweep($target, $mother = true) {
	requireModel('common.setting'); 
	removeServiceSetting('TextcubePSAddon1'); 
	removeServiceSetting('TextcubePSAddon2');
	removeServiceSetting('TextcubePSAddon3');
	return $target;
}
?>
